package net.sf.rose.business.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

import net.sf.rose.business.bean.base.FileBean;
import net.sf.rose.business.bean.control.ViewBean;
import net.sf.rose.exception.SystemErrorCode;
import net.sf.rose.exception.SystemException;
import net.sf.rose.jdbc.KeyGenerator;
import net.sf.rose.jdbc.GenericDAO;
import net.sf.rose.jdbc.QueryBeanSQL;
import net.sf.rose.jdbc.UserBean;
import net.sf.rose.jdbc.service.DataBaseFactory;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateUtil;

import org.apache.log4j.Logger;
import org.simpleframework.xml.ElementMap;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

/**
 * @author fengjian
 * @since 2014/05/25
 */
public class ViewService {

	private static Logger logger = Logger.getLogger(ViewService.class);

	/** 存储在数据库中的名称 */
	private static String NAME = "view_meta";

	/** 存储在数据库中的分类名称 */
	private static String SORT = "config";

	/** 本类的单例 */
	private static ViewService service = null;

	/** 数据类的单例 */
	private static FileBean fileBean = null;

	static {
		Service s = DataBaseFactory.getService();
		UserBean user = new UserBean();
		user.setUserName("system");
		s.setUser(user);
		GenericDAO dao = new GenericDAO(s);
		QueryBeanSQL query = new QueryBeanSQL(s);
		fileBean = new FileBean();
		fileBean.setCode(NAME);
		fileBean.setFileSort(SORT);
		try {
			query.createListSql(fileBean);
			Object obj = dao.load(query);
			if (obj != null) {
				fileBean = (FileBean) obj;
				InputStream in = fileBean.getFile();
				if (in != null) {
					Serializer serializer = new Persister();
					service = serializer.read(ViewService.class, in);
					logger.info("成功地从数据库中读取了视图定义！");
				}
			}
			if (service == null) {
				service = new ViewService();
				logger.info("视图定义初始化...");
			}
		} catch (SystemException e) {
			logger.error("视图初始化从数据库读取时操作失败！", e);
			throw e;
		} catch (Exception e) {
			String message = "视图初始化失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.APPLICATION_ERROR);
		} finally {
			s.close();
		}
	}

	/**
	 * 
	 */
	public static void save(UserBean user) {
		Service s = DataBaseFactory.getService();
		GenericDAO dao = new GenericDAO(s);
		QueryBeanSQL query = new QueryBeanSQL(s);
		try {
			Serializer serializer = new Persister();
			File file = new File(System.getenv("TEMP"), KeyGenerator.getUID());
			serializer.write(service, file);
			InputStream in = new FileInputStream(file);
			fileBean.setFile(in);
			if (fileBean.getFileID() == null) {
				fileBean.setFileID(KeyGenerator.getUID());
				fileBean.setCreateUser(user.getUserName());
				fileBean.setCreateTime(DateUtil.getTimestamp());
				query.createInsertSql(fileBean);
			} else {
				fileBean.setUpdateUser(user.getUserName());
				fileBean.setUpdateTime(DateUtil.getTimestamp());
				query.createUpdateSql(fileBean);
			}
			dao.update(query);
			s.commit();
		} catch (SystemException e) {
			logger.error("视图保存至数据库操作失败！", e);
			throw e;
		} catch (Exception e) {
			String message = "视图保存失败！";
			logger.error(message, e);
			throw new SystemException(message, SystemErrorCode.APPLICATION_ERROR);
		} finally {
			s.close();
		}
	}

	public static Map<String, ViewBean> getAll() {
		return service.views;
	}

	/** 所有定义的Action */
	@ElementMap(required = false)
	private Map<String, ViewBean> views = new LinkedHashMap<String, ViewBean>();

	public Map<String, ViewBean> getViews() {
		return views;
	}

	public void setViews(Map<String, ViewBean> views) {
		this.views = views;
	}

}
